package org.magpiebrain.bittyweb


import org.eclipse.jetty.server.handler.AbstractHandler
import org.eclipse.jetty.server.Handler
import org.eclipse.jetty.server.Server
import org.eclipse.jetty.server.Request

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import scala.xml.Elem
import java.net.ServerSocket

class HttpServer(port: Int) {
  
  val handler = new MutableHandler()
  val server = new Server(port)
  
  def run() = {
    server.setHandler(handler)
    server.start()
  }
  
  /**
   * This response will be used for all communications
   */
  def updateHtml(html: Elem) = {
    handler.html = html
  }
  
  def denyPost = {}
  def denyGet = {}
  def denyHead = {}
  def denyOptions = {}
  def denyPut = {}
  def denyDelete = {}
  def denyTrace = {}
  def denyConnect = {}
  
  
  def throw404 = {
    handler.responseCode = HttpServletResponse.SC_NOT_FOUND
  }
  
  def shutdown = {
    server.stop()
  }
}

object HttpServer {
  def usingRandomFreePort: HttpServer = {
    val socket = new ServerSocket(0)
    val port = socket.getLocalPort()
    socket.close()
    return new HttpServer(port)
  }
}

protected class MutableHandler extends AbstractHandler {
  var html = <h1>Hello</h1>
  var responseCode = HttpServletResponse.SC_OK
    
  override def handle(target: String, request: HttpServletRequest, response: HttpServletResponse) = {
	response.setContentType("text/html");
	response.setStatus(responseCode);
	response.getWriter().println(html.toString());
	(request.asInstanceOf[Request]).setHandled(true);
  }
}
